/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pt.iasd.youthshelter.datacore.controller;

import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import pt.iasd.youthshelter.datamodel.Investiture;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import org.openide.util.lookup.ServiceProvider;
import pt.iasd.youthshelter.datacore.EntityManagerSemaphore;
import pt.iasd.youthshelter.datacore.controller.exceptions.IllegalOrphanException;
import pt.iasd.youthshelter.datacore.controller.exceptions.NonexistentEntityException;
import pt.iasd.youthshelter.datamodel.Lider;
import pt.iasd.youthshelter.datamodel.service.LiderController;

/**
 *
 * @author Rui
 */
@ServiceProvider(service=LiderController.class)
public class LiderJpaController implements Serializable, LiderController {

    private EntityManager aquireEntityManager() throws InterruptedException {
        EntityManagerSemaphore.getInstance().getSemaphore().acquire();
        return EntityManagerSemaphore.getInstance().getEntityManager();
    }
    
    private void releaseEntityManager(EntityManager em) {
        if (em != null && em.isOpen()) {
            em.close();
        }
        EntityManagerSemaphore.getInstance().getSemaphore().release();
    }

    @Override
    public void create(Lider lider) {
        if (lider.getInvestitureList() == null) {
            lider.setInvestitureList(new ArrayList<Investiture>());
        }
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            em.getTransaction().begin();
            List<Investiture> attachedInvestitureList = new ArrayList<Investiture>();
            for (Investiture investitureListInvestitureToAttach : lider.getInvestitureList()) {
                investitureListInvestitureToAttach = em.getReference(investitureListInvestitureToAttach.getClass(), investitureListInvestitureToAttach.getId());
                attachedInvestitureList.add(investitureListInvestitureToAttach);
            }
            lider.setInvestitureList(attachedInvestitureList);
            em.persist(lider);
            for (Investiture investitureListInvestiture : lider.getInvestitureList()) {
                Lider oldLiderIdOfInvestitureListInvestiture = investitureListInvestiture.getLiderId();
                investitureListInvestiture.setLiderId(lider);
                investitureListInvestiture = em.merge(investitureListInvestiture);
                if (oldLiderIdOfInvestitureListInvestiture != null) {
                    oldLiderIdOfInvestitureListInvestiture.getInvestitureList().remove(investitureListInvestiture);
                    em.merge(oldLiderIdOfInvestitureListInvestiture);
                }
            }
            em.getTransaction().commit();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
    }

    @Override
    public void edit(Lider lider) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            em.getTransaction().begin();
            Lider persistentLider = em.find(Lider.class, lider.getId());
            List<Investiture> investitureListOld = persistentLider.getInvestitureList();
            List<Investiture> investitureListNew = lider.getInvestitureList();
            List<String> illegalOrphanMessages = null;
            for (Investiture investitureListOldInvestiture : investitureListOld) {
                if (!investitureListNew.contains(investitureListOldInvestiture)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Investiture " + investitureListOldInvestiture + " since its liderId field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            List<Investiture> attachedInvestitureListNew = new ArrayList<Investiture>();
            for (Investiture investitureListNewInvestitureToAttach : investitureListNew) {
                investitureListNewInvestitureToAttach = em.getReference(investitureListNewInvestitureToAttach.getClass(), investitureListNewInvestitureToAttach.getId());
                attachedInvestitureListNew.add(investitureListNewInvestitureToAttach);
            }
            investitureListNew = attachedInvestitureListNew;
            lider.setInvestitureList(investitureListNew);
            lider = em.merge(lider);
            for (Investiture investitureListNewInvestiture : investitureListNew) {
                if (!investitureListOld.contains(investitureListNewInvestiture)) {
                    Lider oldLiderIdOfInvestitureListNewInvestiture = investitureListNewInvestiture.getLiderId();
                    investitureListNewInvestiture.setLiderId(lider);
                    investitureListNewInvestiture = em.merge(investitureListNewInvestiture);
                    if (oldLiderIdOfInvestitureListNewInvestiture != null && !oldLiderIdOfInvestitureListNewInvestiture.equals(lider)) {
                        oldLiderIdOfInvestitureListNewInvestiture.getInvestitureList().remove(investitureListNewInvestiture);
                        em.merge(oldLiderIdOfInvestitureListNewInvestiture);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = lider.getId();
                if (findLider(id) == null) {
                    throw new NonexistentEntityException("The lider with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            releaseEntityManager(em);
        }
    }

    @Override
    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            em.getTransaction().begin();
            Lider lider;
            try {
                lider = em.getReference(Lider.class, id);
                lider.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The lider with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<Investiture> investitureListOrphanCheck = lider.getInvestitureList();
            for (Investiture investitureListOrphanCheckInvestiture : investitureListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Lider (" + lider + ") cannot be destroyed since the Investiture " + investitureListOrphanCheckInvestiture + " in its investitureList field has a non-nullable liderId field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(lider);
            em.getTransaction().commit();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
    }

    @Override
    public List<Lider> findLiderEntities() {
        return findLiderEntities(true, -1, -1);
    }

    @Override
    public List<Lider> findLiderEntities(int maxResults, int firstResult) {
        return findLiderEntities(false, maxResults, firstResult);
    }

    private List<Lider> findLiderEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Lider.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
        return null;
    }

    @Override
    public List<Lider> findActiveLiderEntities() {
        return findActiveLiderEntities(true, -1, -1);
    }

    @Override
    public List<Lider> findActiveLiderEntities(int maxResults, int firstResult) {
        return findActiveLiderEntities(false, maxResults, firstResult);
    }

    private List<Lider> findActiveLiderEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            CriteriaBuilder cb = em.getCriteriaBuilder();
            CriteriaQuery cq = cb.createQuery();
            Root<Lider> root = cq.from(Lider.class);
            cq.select(root);
            cq.where(cb.isNull(root.get(root.getModel().getSingularAttribute("endDate", Date.class))));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
        return null;
    }

    @Override
    public Lider findLider(Integer id) {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            return em.find(Lider.class, id);
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
        return null;
    }

    @Override
    public int getLiderCount() {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Lider> rt = cq.from(Lider.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
        return 0;
    }
}
